using zhwy.saas.api.Entity.Sys;
using zhwy.saas.api.Extensions.Log;
using zhwy.saas.api.Repository;
using zhwy.saas.api.Services.Sinterface.Sys;

namespace zhwy.saas.api.Services.Sys
{
    /// <summary>
    /// 用户角色关联服务实现
    /// </summary>
    public class SysUserRoleService : BaseService<Users_rolesEntity>, ISysUserRoleService
    {
        private readonly ISysRoleService _sysRoleService;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="repository">用户角色关联仓储接口</param>
        /// <param name="logger">日志服务</param>
        public SysUserRoleService(IBaseRepository<Users_rolesEntity> repository, ILogExt logger,
            ISysRoleService sysRoleService)
            : base(repository, logger)
        {
            _sysRoleService = sysRoleService;
        }

        /// <summary>
        /// 批量分配用户角色
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="roleIds">角色ID列表</param>
        /// <returns>是否分配成功</returns>
        public async Task<bool> AssignRolesAsync(long userId, List<int> roleIds)
        {
            try
            {
                // 先删除原有的角色
                await RemoveUserRolesAsync(userId);

                // 添加新的角色
                var userRoles = roleIds.Select(rid => new Users_rolesEntity
                {
                    Users_id = userId,
                    Role_id = rid
                }).ToList();

                foreach (var ur in userRoles)
                {
                    await _repository.AddAsync(ur);
                }

                return true;
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"分配用户[{userId}]角色失败");
                return false;
            }
        }

        /// <summary>
        /// 移除用户的所有角色
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>是否移除成功</returns>
        public async Task<bool> RemoveUserRolesAsync(long userId)
        {
            try
            {
                // 删除用户的所有角色
                var existingRoles = await _repository.GetListAsync(ur => ur.Users_id == userId);
                foreach (var role in existingRoles)
                {
                    await _repository.DeleteAsync(role);
                }
                return true;
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"移除用户[{userId}]角色失败");
                return false;
            }
        }

        /// <summary>
        /// 获取用户的角色ID列表
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>角色ID列表</returns>
        public async Task<List<int>> GetRoleIdsByUserIdAsync(long userId)
        {
            var userRoles = await _repository.GetListAsync(ur => ur.Users_id == userId);
            return userRoles.Select(ur => ur.Role_id).ToList();
        }

        /// <summary>
        /// 检查用户是否拥有指定角色
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="roleId">角色ID</param>
        /// <returns>是否拥有角色</returns>
        public async Task<bool> HasRoleAsync(long userId, int roleId)
        {
            var userRole = await _repository.GetListAsync(ur =>
                ur.Users_id == userId && ur.Role_id == roleId);
            return userRole != null;
        }

        /// <summary>
        /// 租户添加默认角色
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<bool> AddTeanantRoleAsync(long userId)
        {
            var role = await _sysRoleService.GetTenantDefaultInfo();
            if (role == null)
            {
                return false;
            }
            //添加角色
            return await _repository.AddAsync(new Users_rolesEntity()
            {
                Role_id = role.Id,
                Users_id = userId,
            });
        }
    }
}